"""存储服务 - 专注于运行时数据的KV存储管理"""

import kv
import config
import ujson
import utime as time

MIN_TIMESTAMP = 1735660800


class RuntimeStorage:
    """存储服务管理器 - 专注于运行时数据的存储和KV管理"""

    def __init__(self):
        self.kv_initialized = False

    def init_kv_storage(self):
        """初始化KV存储"""
        try:
            kv.set("__kv_test__", "test")
            kv.get("__kv_test__")
            kv.remove("__kv_test__")
            self.kv_initialized = True
            print("[STORAGE_SERVICE] KV storage initialized")
        except Exception as e:
            print("[STORAGE_SERVICE] KV storage init failed: {}".format(e))
            self.kv_initialized = False

        # 初始化 device_sn（首次启动）
        # self.write_last_timestamp()
        return True

    # def _init_default_device_sn(self):
    #     """从config.json初始化默认device_sn"""
    #     try:
    #         # 检查是否已有device_sn
    #         existing_sn = self.get_device_sn()
    #         if existing_sn and int(existing_sn) >= 10000:
    #             print(
    #                 "[STORAGE_SERVICE] Device SN already exists: {}".format(existing_sn)
    #             )
    #             return

    #         # 从config.json读取默认device_sn
    #         device_info = config.get_device_info()
    #         default_device_sn = device_info.get("device_sn", "10000")

    #         # 设置默认device_sn
    #         self.set_device_sn(default_device_sn)
    #         print(
    #             "[STORAGE_SERVICE] Initialized device_sn from config: {}".format(
    #                 default_device_sn
    #             )
    #         )

    #     except Exception as e:
    #         print(
    #             "[STORAGE_SERVICE] Failed to init default device_sn: {}".format(e)
    #         )  # 返回True表示初始化完成，但使用缓存模式

    def get_kv_config(self, key, default_value=None):
        """获取KV配置值"""
        try:
            value = kv.get(key)
            if value is not None:
                # 尝试JSON解析
                try:
                    return ujson.loads(value)
                except:
                    # 如果不是JSON，直接返回字符串
                    return value
            return default_value
        except Exception as e:
            print("[STORAGE_SERVICE] Get KV config error for key '{}': {}".format(key, e))
            return default_value

    def set_kv_config(self, key, value):
        """设置KV配置值"""
        try:
            if self.kv_initialized:
                # 如果是复杂对象，转换为JSON
                if isinstance(value, (dict, list)):
                    json_value = ujson.dumps(value)
                    kv.set(key, json_value)
                else:
                    kv.set(key, str(value))
                return True
            else:
                print("[STORAGE_SERVICE] KV not initialized, cannot save config")
                return False
        except Exception as e:
            print("[STORAGE_SERVICE] Set KV config error for key '{}': {}".format(key, e))
            return False

    def delete_kv_config(self, key):
        """删除KV配置"""
        try:
            if self.kv_initialized:
                kv.remove(key)
                return True
            else:
                print("[STORAGE_SERVICE] KV not initialized, cannot delete config")
                return False
        except Exception as e:
            print(
                "[STORAGE_SERVICE] Delete KV config error for key '{}': {}".format(key, e)
            )
            return False

    def get_all_keys(self):
        """获取所有配置键"""
        try:
            if self.kv_initialized:
                return kv.getkeys()
            else:
                print("[STORAGE_SERVICE] KV not initialized, cannot get keys")
                return []
        except Exception as e:
            print("[STORAGE_SERVICE] Get all keys error: {}".format(e))
            return []

    def get_kv_storage_info(self):
        """获取存储信息"""
        try:
            if self.kv_initialized:
                keys = self.get_all_keys()
                return {"kv_initialized": True, "total_keys": len(keys), "keys": keys}
            else:
                return {"kv_initialized": False, "total_keys": 0, "keys": []}
        except Exception as e:
            print("[STORAGE_SERVICE] Get storage info error: {}".format(e))
            return {"kv_initialized": False, "total_keys": 0, "keys": []}

    def get_reboot_count(self):
        """获取重启次数"""
        return self.get_kv_config("reboot_count", 0)

    def increment_reboot_count(self):
        """增加重启次数"""
        count = self.get_reboot_count() + 1
        self.set_kv_config("reboot_count", count)
        return count

    def write_last_timestamp(self):
        """Write last timestamp to kv"""
        # 由于RTC现在设置为UTC时间，time.time()应该返回UTC时间戳
        timestamp = time.time()
        
        if timestamp > MIN_TIMESTAMP:
            self.set_kv_config("last_timestamp", timestamp)
            print("[STORAGE] Writing last_timestamp to kv..., {} (UTC)".format(timestamp))
        else:
            print("[STORAGE] Invalid timestamp, not writing to kv: {}".format(timestamp))

    def read_last_timestamp(self):
        """Read last timestamp from kv (returns UTC timestamp)"""
        print("[SYSTEM] Reading last timestamp from kv...")
        timestamp = self.get_kv_config("last_timestamp", 0)
        if timestamp == 0 or timestamp < MIN_TIMESTAMP:
            return 0
        print("[SYSTEM] Read last_timestamp: {} (UTC)".format(timestamp))
        return timestamp


# 全局存储服务实例
runtime_storage = RuntimeStorage()
